from datetime import datetime

from flask import request, Blueprint, json


from app import db
from app.models import User,UserTopicAssociation
from app.models.prompt_model import Prompt
from app.models.user_info_model import UserInfo
from app.utils.Response import Response
from app.utils.Redis import Redis

from app.utils.token_util import get_jwt_token, token_required

# 导入 user_blueprint


user_blueprint = Blueprint('user_blueprint', __name__, url_prefix='/user')


@user_blueprint.route('/register', methods=['POST'])
def register_user():
    data = request.get_json()
    # 获取 JSON 数据
    data = request.get_json()
    if not data:
        return Response.error(501, "注册失败 参数错误").to_dict()

    # 读取字段
    email = data.get('email')
    password = data.get('password')
    verification_code = data.get('verificationCode')

    # 检查必填字段是否存在
    if not all([email, password, verification_code]):
        return Response.error(501, "Missing required fields").to_dict()

    # 在这里可以添加业务逻辑，例如校验验证码、密码验证等

    # 校验验证码
    real_code = Redis.read(email)

    if verification_code != real_code:
        return Response.error(503, "Verification验证码错误或者失效").to_dict()

    ##密码加密
    new_user = User(email=email, password=password, status=0, create_at=datetime.now(), update_at=datetime.now())

    new_user.set_password(password)

    new_user.create_user()

    token = get_jwt_token(new_user.id)

    data = {
        "data": {
            "token": token
        }
    }

    # 1.邮箱验证唯一性
    # 2.参数校验

    return Response(code=200, msg="成功", data=data).to_dict()


@user_blueprint.route('/login', methods=['POST'])
# @token_required
def login():
    # 解析请求体 JSON 数据
    data = request.get_json()
    if not data:
        return Response.error(502, "请求体必须是JSON格式").to_dict()

    # 读取 email 和 password 字段
    email = data.get('email')
    password = data.get('password')

    # 检查必填字段是否存在
    if not email or not password:
        return Response.error(400, "缺少邮箱或密码").to_dict()

    # 业务逻辑：此处添加实际的用户认证逻辑（例如查询数据库验证用户身份）
    user = User.query.filter_by(email=email).first()

    if not user:
        return Response.error(503, "邮箱或密码错误").to_dict()

    # 这里提供一个简单示例，仅作说明
    if email == user.get_email() and user.check_password(password):

        token = get_jwt_token(user.id)

        data = {
            "data": {
                "token": token
            }
        }

        # 登录成功，返回成功响应
        return Response(code=200, msg="登录成功", data=data).to_dict()

    else:
        # 登录失败，返回错误响应
        return Response.error(503, "邮箱或密码错误").to_dict()


@user_blueprint.route('/findPassword', methods=['POST'])
def findPassword():
    data = request.get_json()
    if not data:
        return Response.error(502, "请求体必须是JSON格式").to_dict()

    email = data.get('email')
    newPassword = data.get('newPassword')

    code = data.get('code')
    # 检查必填字段是否存在
    if not all([email, newPassword, code]):
        return Response.error(501, "Missing required fields").to_dict()

    # 校验验证码
    real_code = Redis.read(email)

    if code != real_code:
        return Response.error(503, "验证码错误或者失效").to_dict()

    user = User.query.filter_by(email=email).first()

    user.set_password(newPassword)

    user.update_user()

    return Response.success_static(200, "密码修改成功").to_dict()


@user_blueprint.route('/info/add', methods=['POST'])
@token_required
def addUserInfo(current_user):
    data = request.get_json()
    if not data:
        return Response.error(502, "请求体必须是JSON格式").to_dict()

    try:
        # 数据预处理
        interests = json.dumps(data.get("interests", []))  # 列表转为JSON字符串
        skills = json.dumps(data.get("skills", []))
        achievements = json.dumps(data.get("achievements", []))
        social_media = json.dumps(data.get("socialMedia", {}))
        recent_activities = json.dumps(data.get("recentActivities", []))

        birth_date = datetime.strptime(data.get("birthDate", "1970-01-01"), "%Y-%m-%d")

        # 创建 UserInfo 实例
        user_info = UserInfo(
            user_id=current_user.get_id(),
            full_name=data.get("fullName"),
            birth_date=birth_date,
            gender=data.get("gender"),
            location=data.get("location"),
            occupation=data.get("occupation"),
            bio=data.get("bio"),
            interests=interests,
            avatar=data.get("avatar"),
            education=data.get("education"),
            phone=data.get("phone"),
            email=data.get("email"),
            skills=skills,
            achievements=achievements,
            social_media=social_media,
            recent_activities=recent_activities
        )

        # 保存到数据库
        db.session.add(user_info)
        db.session.commit()
        return Response.success_static(200, "信息保存成功").to_dict()
    except Exception as e:
        db.session.rollback()
        print(f"Error saving UserInfo: {e}")

        return Response.error(200, "信息保存失败").to_dict()


@user_blueprint.route('/info/find', methods=['GET'])
@token_required
def get_info(current_user):
    user_info = UserInfo.query.filter_by(user_id=current_user.get_id()).first()

    return Response(code=200, msg='查询成功', data=user_info.to_dict()).to_dict()


@user_blueprint.route('/info/update', methods=['POST'])
@token_required
def update_user_info(current_user):
    data = request.get_json()
    if not data:
        return Response.error(502, "请求体必须是JSON格式").to_dict()

    # 通过 userId 判断更新哪个用户的信息，注意这里的 userId 与当前登录用户进行对比，
    # 可根据具体业务逻辑进行处理（如只允许当前用户修改自己的信息）
    user_id = data.get("userId")
    if not user_id:
        return Response.error(400, "缺少userId字段").to_dict()

    # 检查是否是当前登录用户
    if user_id != current_user.get_id():
        return Response.error(403, "无权限修改其他用户信息").to_dict()

    user_info = UserInfo.query.filter_by(user_id=user_id).first()
    if not user_info:
        return Response.error(404, "未找到用户信息").to_dict()

    try:
        # 示例仅更新传入的字段，如 fullName、birthDate、gender、skills、achievements、socialMedia、recentActivities
        if "fullName" in data:
            user_info.full_name = data.get("fullName")

        if "birthDate" in data:
            # 注意传入的 birthDate 格式与之前保存的不一致，这里支持 '1987-08-30 23:15:32' 格式
            try:
                user_info.birth_date = datetime.strptime(data.get("birthDate"), "%Y-%m-%d %H:%M:%S")
            except ValueError:
                # 如果解析失败，可考虑返回错误或忽略更新
                return Response.error(400, "birthDate格式错误，正确格式应为 YYYY-MM-DD HH:MM:SS").to_dict()

        if "gender" in data:
            user_info.gender = data.get("gender")

        if "skills" in data:
            # skills 为列表类型，转为 JSON 字符串
            user_info.skills = json.dumps(data.get("skills", []))

        if "achievements" in data:
            user_info.achievements = json.dumps(data.get("achievements", []))

        if "socialMedia" in data:
            user_info.social_media = json.dumps(data.get("socialMedia", {}))

        if "recentActivities" in data:
            # recentActivities 可能为 null，这里判断
            if data.get("recentActivities") is None:
                user_info.recent_activities = None
            else:
                user_info.recent_activities = json.dumps(data.get("recentActivities", []))

        # 可根据需要扩展其他字段更新逻辑，比如 avatar、bio 等

        db.session.commit()
        return Response.success_static(200, "信息更新成功").to_dict()
    except Exception as e:
        db.session.rollback()
        print(f"Error updating UserInfo: {e}")
        return Response.error(500, "信息更新失败").to_dict()


@user_blueprint.route('/prompt', methods=['GET'])
@token_required
def get_prompt(current_user):
    # 查询所有 Prompt 并返回
    prompts = Prompt.query.all()
    result = [prompt.to_dict() for prompt in prompts]

    return Response(200,msg="查询成功",data=result).to_dict()

@user_blueprint.route('/topics',methods=['GET'])
@token_required
def get_topics(current_user):
    user_topics = UserTopicAssociation.query.filter_by(user_id=current_user.get_id()).all()

    return Response(200, msg="查询成功",data=user_topics).to_dict()